import { _decorator, Component, Sprite, UITransform } from 'cc';
import { DIRECTION_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_ENUM, PARAMS_NAME_ENUM, PLAYER_DEAD_TYPE } from '../../Enum';
import { TILE_WEIGHT, TILE_HEIGHT } from '../Tile/TileItem';
import { EntiyManager } from '../../common/EnityManager';
import { EventManager } from '../../RunTime/EventManager';
import { DataManager } from '../../RunTime/DataManager';
import { ISpikes } from '../../Levels';
import { SpikesStateMachine } from './SpikesStateMachines';
import { StateMachine } from '../../common/StateMachine';
const { ccclass, property } = _decorator;


@ccclass('SpikesManager')
export class SpikesManager extends Component {

  x: number = 0
  y: number = 0
  fsm: StateMachine
  type: ENTITY_TYPE_ENUM
  private _currentCnt: number
  private _totalCnt: number

  get currentCnt(): number {
    return this._currentCnt
  }
  set currentCnt(value: number) {
    this._currentCnt = value
    this.fsm.setParam(PARAMS_NAME_ENUM.SPIKES_CURRENT_CNT,value)
  }

  get totalCnt(): number {
    return this._totalCnt
  }
  set totalCnt(value: number) {
    this._totalCnt = value
    this.fsm.setParam(PARAMS_NAME_ENUM.SPIKES_TOTAL_CNT, value)
  }

  async init(ispikes: ISpikes){
    this.fsm = this.addComponent(SpikesStateMachine)
    await this.fsm.init()
    const sprite = this.addComponent(Sprite)
    sprite.sizeMode = Sprite.SizeMode.CUSTOM
    this.getComponent(UITransform).setContentSize(TILE_WEIGHT, TILE_HEIGHT)
    const {x,y,currentCnt,totalCnt} = ispikes
    this.x = x
    this.y = y
    this.totalCnt = totalCnt + 1
    this.currentCnt = currentCnt
    this.node.setPosition(this.x * TILE_WEIGHT, -this.y * TILE_HEIGHT)
    EventManager.getInstance().on(EVENT_ENUM.PLAYER_MOVE_END, this.onLoop, this)
  }

  onDestroy() {
    EventManager.getInstance().off(EVENT_ENUM.PLAYER_MOVE_END, this.onLoop)
  }

  onLoop() {
    //达到最大值会在动画回调置0，当最大值时还没归零但人又触发移动，就让他变成1就好了
    if (this.currentCnt == this.totalCnt) {
      this.currentCnt = 0
    } else {
      this.currentCnt++
    }
    this.onAttack()
  }

  backZero() {
    this.currentCnt = 0
  }

  onAttack() {
    const { x: playerX, y: playerY } = DataManager.getInstance().player
    if (playerX === this.x && playerY === this.y && this.currentCnt === this.totalCnt) {
      EventManager.getInstance().emit(EVENT_ENUM.PLAYER_DIE, ENTITY_STATE_ENUM.DEAD)
    }
  }







}
